package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Override
    public void execute(ShardingContext shardingContext) {
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String type) {
        // 远程调用秒杀服务查询数据
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByType(Integer.parseInt(type));
        /**
         * result有三种情况
         * 1.如果调用服务挂掉了，直接走降级方法，返回值为null
         * 2.调用服务出现了异常，被统一异常处理
         * 3.正常返回
         */
        if (result != null && !result.hasError()) {
            // 把查询数据放到redis中
            List<SeckillProductVo> seckillProductVoList = result.getData();
            for (SeckillProductVo seckillProductVo : seckillProductVoList) {
                redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(type),seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));
                // 把库存放到redis中
                redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(type),seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
            }
            System.out.println("数据同步成功");
        }
    }
}